# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import smtplib

from redis import Redis
from scrapy.exceptions import DropItem
from email.mime.text import MIMEText
from email.header import Header


class HkdPipeline(object):
    def __init__(self):
        self.r = Redis(host='localhost', port=6379, db=1, password='5tgbnhy67ujm')

    def process_item(self, item, spider):
        if spider.name == 'hkdnotify':
            check = self.r.sadd('notify:hkd', item)
            if check:
                from_addr = '18437958356@163.com'
                passwd = 'cz9277'
                to_addr = '18437958356@163.com'
                _server = 'smtp.163.com'
                con_model = '''
                    最新%s
                        正文：%s
                        链接：%s
                        日期：%s
                '''
                msg = MIMEText(con_model % (item['type'], item['title'], item['url'], item['ntime']), 'plain', 'utf-8')
                msg['from'] = Header(item['type'], 'utf-8')
                msg['to'] = Header(to_addr, 'utf-8')
                msg['subject'] = "%s:%s" % (item['type'], item['title'])
                server = smtplib.SMTP_SSL(_server, 465)
                server.set_debuglevel(1)
                server.login(from_addr, passwd)
                try:
                    server.sendmail(from_addr, to_addr, msg.as_string())
                    print("is ok ")
                except:
                    print("send is error")
                finally:
                    server.quit()
            else:
                raise DropItem('%s is in database' % item['title'])
        else:
            pass
        return item

class NotifyPipeline(object):
    def process_item(self, item, spider):
        return item
